<template>
    <div class="chat-float" v-bind:class="{chatExpand:this.show}" @click.stop="openChat">
        <div v-if="!show"
             style="font-size: 28px;margin-left: 10px;margin-top:5px;width: 100%">
            <el-badge :hidden="unread===0" :value="unread" :max="99" class="item">
                <i class="el-icon-chat-dot-square"></i>
            </el-badge>
        </div>
        <Chat
            :unread="unread"
            ref="chat"
            v-bind:pin="pin"
            :userList="userlist"
            v-on:setCurrentChatUserId="setCurrentChatUserId"
            v-on:lockClose="lockClose"
            v-on:togglePin="togglePin"
            v-on:closeChat="closeChat"
            v-on:refreshMessage="refreshMessage"
            v-if="show"/>
    </div>
</template>

<script>
import Chat from "@/components/Chat/Chat";
import Header from "@/components/Header/Header";
import Sider from "@/components/Sider/Sider";
import axios from "@/utils/http";

export default {
    name: "ChatComponent",
    components: {Chat},
    data() {
        return {
            show: false,
            pin: false,
            lock: false,
            socket: {},
            userid: -1,
            currentChatUserid: -1,
            userlist: [],
            unread: 0,
        }
    },
    methods: {
        //
        //websocket
        init: function () {
            if (!this.$store.getters.isConnected) {
                var id = this.$store.getters.getUser.id
                this.userid = id

                if (typeof (WebSocket) === "undefined") {
                    this.$message.error("您的浏览器不支持socket")
                } else {
                    // 实例化socket
                    this.socket = new WebSocket("ws://172.18.9.159:10007/websocket/" + id)
                    // this.socket = new WebSocket("ws://39.105.147.252:10007/websocket/" + id)
                    // 监听socket连接
                    this.socket.onopen = this.open
                    // 监听socket错误信息
                    this.socket.onerror = this.error
                    // 监听socket消息
                    this.socket.onmessage = this.getMessage
                    this.socket.onclose = this.close
                    console.log(this.socket)
                    this.$store.dispatch("setWebSocket", this.socket)
                    this.$store.dispatch("openConnect")
                    this.$axios.get("/chat/chat/getTodayMessageList", {
                        params: {
                            'id': id
                        }
                    }).then(e => {
                        var userlist = e.data.obj
                        this.userlist = userlist
                    })
                }
            } else {
                console.log('websocket has connected')
            }
        },
        open: function () {
            //发送心跳
            let _this = this;

            console.log("socket连接成功")
        },
        error: function () {
            console.log("连接错误")
        },
        getMessage: function (msg) {
            var message
            if (msg.data.charAt(0) === '0') {
                this.$notify.info({
                    title: '提示',
                    message: msg.data.substring(1),
                    duration: 2000,
                    offset: 100
                });
            }
            message = JSON.parse(msg.data)
            console.log(this.currentChatUserid)

            if (this.currentChatUserid === message.msgFrom) {
                //如果msg发送给当前窗口
                //设置发送信息状态为已读
                this.$axios.post('/chat/chat/setMessageRead', [message.msgId]).then(e => {
                    console.log(e)
                    this.refreshMessage()
                    message.msgRead = 1
                    this.$refs.chat.receiveMessage(message)

                })


            } else {
                this.refreshMessage()
            }

            this.$notify.info({
                title: '您有一条新消息',
                message: message.msgContent,
                duration: 2000,
                offset: 100
            });
            console.log(message.msgContent)
        },
        close: function () {
            console.log("socket已经关闭")
        },


        //与子组件通信
        setCurrentChatUserId(id) {

            console.log(id)
            this.currentChatUserid = id
        },
        openChat() {
            this.show = true
        },
        togglePin() {
            this.pin = !this.pin;

        },
        closeChat() {
            console.log("chat window close")
            this.show = false
            this.pin = false
            this.currentChatUserid = -1
        },
        lockClose() {
            this.lock = true
        },
        refreshMessage() {
            console.log('refresh message')
            this.$axios.get("/chat/chat/getTodayMessageList", {
                params: {
                    'id': this.userid
                }
            }).then(e => {
                console.log(e)
                var userlist = e.data.obj
                this.userlist = userlist
            })
        }

    },
    mounted() {
        document.getElementById("bbb").addEventListener('click', () => {
            if (!this.pin && !this.lock)
                this.show = false;
        }, false);
        this.init()


    },
    destroyed() {
        console.log("destory")
        this.socket.close()
        this.$store.dispatch("closeConnect")

    },
    watch: {
        userlist: {
            handler(val, oldVal) {
                var total = 0;
                val.forEach(u => {
                    var tt = 0;
                    u.todayMessage.forEach(i => {
                        if (i.msgRead === 0 && i.msgTo === this.userid) {
                            tt++;
                            total++;
                        }
                    })
                    u.unread = tt
                })
                this.unread = total

                console.log("watch value change")
            },
            deep: true
        }
    }
}
</script>

<style scoped>
.chat-float {
    position: absolute;
    width: 50px;
    height: 50px;
    background-color: #ffffff;
    right: 20px;
    top: 85%;
    transition: all ease-in-out 300ms;
    border-radius: 50px;
    box-shadow: 0px 1px 5px 0px rgba(0, 0, 0, 0.2);
    cursor: pointer;
    z-index: 999;

}


.chatExpand {
    height: 800px;
    width: 500px;
    top: 10%;

    border-radius: 0;
    cursor: auto;
}
</style>